/*
 *    Copyright(c)2023-2024
 *    项目名称:hello-world
 *    文件名称:SysMenuServiceImpl.java
 *    Date:2023/11/26 下午7:23
 *    Author:赵士杰
 */

package com.hw.system.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hw.common.utils.bean.BeanCopyUtils;
import com.hw.system.admin.mapper.SysMenuMapper;
import com.hw.system.admin.pojo.SysMenu;
import com.hw.system.admin.service.ISysMenuService;
import com.hw.system.admin.vo.SysMenuTreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author 赵士杰
 * @since 2023-11-26 09:40:05
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<String> getUserPermissions(Long userId) {
        return sysMenuMapper.getUserPermissions(userId);
    }

    @Override
    public List<SysMenuTreeVo> getUserMenuTree(Long userId) {
        List<SysMenu> menuList = sysMenuMapper.getUserMenuTree(userId);
        return buildMenuTree(menuList, 0L);
    }

    /**
     * 构建菜单树
     *
     * @param menuList 菜单列表
     * @param parentId 父节点ID
     * @return 菜单树列表
     */
    private List<SysMenuTreeVo> buildMenuTree(List<SysMenu> menuList, Long parentId) {
        List<SysMenuTreeVo> treeList = new ArrayList<>();
        for (SysMenu menu : menuList) {
            if (parentId.equals(menu.getParentId())) {
                SysMenuTreeVo tree = BeanCopyUtils.copyBean(menu, SysMenuTreeVo.class);
                List<SysMenuTreeVo> children = buildMenuTree(menuList, menu.getMenuId());
                if (!children.isEmpty()) {
                    tree.setChildren(children);
                }
                treeList.add(tree);
            }
        }
        return treeList;
    }

}
